const assert = require("http-assert");
const jwt = require("jsonwebtoken");
const adminUser = require("../model/AdminUser");
module.exports = (app) => {
    return async (req, res, next) => {

        //对接口的token校验

        const token = req.headers.token?.split(' ').pop()
        //token不存在
        assert(token,401,'请先登录')
        const jwtMsg = jwt.verify(token, app.get('secret'),(err,decod)=>{

            //token失效进入该报错
            if ( err && err.name === 'TokenExpiredError'){
                console.log('过期')
                return  {
                    type:'TokenExpiredError',
                    msg:'登录过期,请重新登录'
                }
            } else if ( err && err.name === 'JsonWebTokenError' || err) {
                return {
                    type:'JsonWebTokenError',
                    msg:'验证错误,请重新登录'
                }
            } else {
                return decod
            }
        })


        //tooken过期
        assert(jwtMsg.type !== 'TokenExpiredError',401,jwtMsg.msg)
        assert(jwtMsg.type !== 'JsonWebTokenError',401,jwtMsg.msg)

        req.user = await adminUser.findById(jwtMsg.id)
        await next()
    }
}